package com.jsonal.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import com.alibaba.fastjson.JSONObject;
import com.jsonal.common.HttpUtil;
import com.jsonal.entity.MyToken;
import com.jsonal.util.RedisUtil;
import com.jsonal.vo.Result;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: jsonal
 * @Description:
 * @Date: 2020/11/18 15:42
 * @Version: 1.0
 */
@Slf4j
@RestController
public class SSOController {

    private static final String CLIENT_ID = "myblog";
    private static final String CLIENT_SECRET = "myblogsecret";
    private static final String REDIRECT_URI = "http://localhost:8081/sso";
    private static final String SSO_URL = "http://localhost:7777/uaa/oauth/authorize";
    private static final String ACCESS_TOKEN = "http://localhost:7777/uaa/oauth/token";
    private static final String GET_USER_URL = "http://localhost:7777/uaa/user";
    private static final String ERROR_PAGE = "http://localhost:8080/404";
    private static final String API_INDEX_PAGE = "http://localhost:8080/index";

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/api/toSso", method = GET)
    @CrossOrigin
    public String toSso(HttpServletRequest request, HttpServletResponse response) throws IOException {
        long time = System.currentTimeMillis();
        String url =SSO_URL+"?" +
            "client_id="+CLIENT_ID 								  //OAuth客户端的ID
            + "&response_type=code&" +                                    //固定写法，不要变
            "redirect_uri="+REDIRECT_URI+"&" +	//OAuth客户端的回调地址
            "oauth_timestamp="+time;//时间戳
        log.info("url>>>>>>>>>{}", url);
//        String result = HttpUtil.sendGet(url, null);
        return url;
    }


    @RequestMapping(value = "/sso", method = GET)
    @CrossOrigin
    public void sso(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Result result = new Result();
        String code = req.getParameter("code");
        log.info("SSO 返回的 CODE>>>>>>>>>>>>>>>" + code);
        String str = getToken(code);
        log.info("通过CODE获取的token>>>>>>" + str);
        if ("".equals(str) || "null".equals(str) || str.contains("error")) {
            resp.sendRedirect(ERROR_PAGE);
        }
        MyToken token = JSONObject.parseObject(str, MyToken.class);
        // 因为是前后端分离 所以不需要走登录页面 所以获取不到用户信息
//        String userJson = getUserInfo(token.getAccess_token());
//        log.info("通过token获取的用户>>>>>>" + userJson);
//        if ("".equals(userJson) || "null".equals(userJson)) {
//            return new Result(false, "用户不存在");
//        }
        redisUtil.set("token", token.getAccess_token(), Long.parseLong(token.getExpires_in()));
        Cookie cookie = new Cookie("token", token.getAccess_token());
        cookie.setPath("/");


        resp.addCookie(cookie);
        resp.sendRedirect(API_INDEX_PAGE);
    }

    private String getUserInfo(String token) {
        log.info("token>>>>>>>>>>>> {}", token);
        String sendGet = HttpUtil.sendGet(GET_USER_URL + "?access_token=" + token, null);
        return sendGet;
    }

    /**
     * 第三步，根据code换取access_token
     */
    public String getToken(String code) {
        String token = "";
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("code", code);
            data.put("client_id", CLIENT_ID);
            data.put("grant_type", "authorization_code");
            data.put("client_secret", CLIENT_SECRET);
            data.put("redirect_uri", REDIRECT_URI);
            String result = HttpUtil.sendPost(ACCESS_TOKEN, null, data);
            log.info(result);
            if (!result.isEmpty()) {
                token = result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
}
